package org.example.userservice.Impl;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.feign.pojo.Customer;
import org.example.feign.pojo.Employees;
import org.example.feign.pojo.MyEntity;
import org.example.feign.pojo.Result;
import org.example.userservice.mapper.Mapper;
import org.example.userservice.service.PojoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Service
public class PojoServiceImpl implements PojoService {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    //2.创建sqlSessionFactoryBuilder对象，这个对象用来创建工厂
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    //3.创建工厂，用来生产sqlSession
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    SqlSession sqlSession;
    @Resource
    private Mapper customerMapper;

    public PojoServiceImpl() throws IOException {
    }

    public List<? extends Object> inpojo(String Spojo) {

        if (Spojo.equals("cus")) {
            List<Customer> pojo = mybatisopen().getCus();
            mybatisclose();
            return pojo;
        } else if (Spojo.equals("employees")) {
            List<Employees> pojo = mybatisopen().login();
            mybatisclose();
            return pojo;
        } else {
            return new ArrayList<>();
        }

    }



    @Override
    public int result(MyEntity entity) {
     int  result=mybatisopen().updataPrice(entity);
        System.out.println("影响行数："+result);
        mybatisclose();
     return result;
    }

    public Mapper mybatisopen() {

        //4.获取sqlSession，sqlSession表示Java程序和数据库之间的会话
        sqlSession = sqlSessionFactory.openSession();
        //5.获取CustomerMapper接口对象，这个方法底层用代理模式返回了接口实现类的对象
        Mapper Mapper = sqlSession.getMapper(Mapper.class);
        System.out.println("mybatis 打开成功");
        return Mapper;
    }

    public void mybatisclose() {
        sqlSession.commit();
        //8.关闭会话
        sqlSession.close();
        System.out.println("mybatis 关闭成功");

    }
    public Result getPojo(String Spojo) {
        return Result.success(inpojo(Spojo));
    }

}
